package sc.web.util;

import org.apache.commons.lang.StringUtils;
import org.springframework.security.Authentication;
import org.springframework.security.GrantedAuthority;
import org.springframework.security.context.SecurityContext;
import org.springframework.security.context.SecurityContextHolder;

import sc.core.model.auth.UserToken;

public class UserUtil {

	public static UserToken getUserToken() {
		SecurityContext ctx = SecurityContextHolder.getContext();
		if (ctx == null)
			return null;
		Authentication auth = ctx.getAuthentication();
		if (auth == null)
			return null;
		Object userToken = auth.getPrincipal();
		if (userToken == null)
			return null;
		return (UserToken) userToken;
	}

	public static String getLoginName() {
		UserToken userToken = getUserToken();
		if (userToken == null)
			return null;
		return userToken.getUsername();

	}

	public static boolean hasPermission(String permissionKey) {
		UserToken userToken = getUserToken();
		if (userToken == null)
			return false;
        for (GrantedAuthority grantedAuthority : userToken.getAuthorities()) {
            if (StringUtils.equals(permissionKey, grantedAuthority.getAuthority())) {
                return true;
            }
        }
        return false;
	}
}
